package school.repository;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import com.ibm.db2.jcc.a.SqlException;

import school.domain.TheoryLesson;

public class JdbcTheoryLessonDao implements TheoryLessonDao {

	@Override
	public ArrayList<TheoryLesson> getByGroupId(int groupId) throws Exception {
		Connection con = JdbcUtil.connect();
		ArrayList<TheoryLesson> theoryLessons = new ArrayList<TheoryLesson>();
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

		String sql = "CALL Get_Theory_Lessons_By_Group_Id(?)";
		CallableStatement prepCall = con.prepareCall(sql);

		prepCall.setInt(1, groupId);

		try {
			ResultSet rs = prepCall.executeQuery();

			while(rs.next()) {
				TheoryLesson theoryLesson = new TheoryLesson();
				
				theoryLesson.setGroupId(groupId);
				theoryLesson.setLessonDate(dateFormat.format(rs.getDate(1)));
				theoryLesson.setLessonStatus(rs.getString(2));
				theoryLesson.setLessonTime(rs.getTime(3).toString());
				theoryLesson.setPrice(rs.getDouble(4));
				theoryLesson.setRoom(rs.getInt(5));
				theoryLesson.setId(rs.getInt(6));
				
				theoryLessons.add(theoryLesson);
			}
		} catch (SqlException e) {
			e.printStackTrace();
			throw e;
		} catch (Exception e) {
			throw e;
		} finally {
			JdbcUtil.disconnect();
		}

		return theoryLessons;
	}
}
